<template>
   <div class='space-y-2'>
        <div v-if="label" class='mb-1 flex items-center justify-between'>
          <div class='system-xs-medium-uppercase flex h-6 items-center text-text-tertiary'>{label}</div>
            <Button v-if="isArrayLikeType" @click="handleAddContext"><PlusOutlined /> </Button>
        </div>
          <FormItem v-for="(input, index) in inputs"
            inStepRun
            :key="index"
            :payload="input"
            :value="values[input.variable]"
            @change="handleChange(input.variable)" 
          />
    </div>
</template>
<script setup lang="ts" name="Form">
import type { InputVar } from '../../../../types'
import FormItem from './form-item.vue'
import { InputVarType } from '@/app/components/workflow/types'
import { RETRIEVAL_OUTPUT_STRUCT } from '@/app/components/workflow/constants'
import { PlusOutlined } from '@ant-design/icons-vue'
import { computed,ref } from 'vue'

export type Props = {
  label?: string
  inputs: InputVar[]
  values: Record<string, string>
  onChange: (newValues: Record<string, any>) => void
}

const props = defineProps<Props>();

  const mapKeysWithSameValueSelector = computed(() => {
    const keysWithSameValueSelector = (key: string) => {
      const targetValueSelector = props.inputs.find(
        item => item.variable === key,
      )?.value_selector
      if (!targetValueSelector)
        return [key]

      const result: string[] = []
      props.inputs.forEach((item) => {
        if (item.value_selector?.join('.') === targetValueSelector.join('.'))
          result.push(item.variable)
      })
      return result
    }
    const m = new Map()
    for (const input of props.inputs)
      m.set(input.variable, keysWithSameValueSelector(input.variable))

    return m
  })


  const handleChange = (key: string) => {
    const mKeys = mapKeysWithSameValueSelector.value.get(key) ?? [key]
    return (value: any) => {
        for (const k of mKeys)
           props.values[k] = value
      props.onChange(props.values)
    }
  }
  const isArrayLikeType = computed(()=> [InputVarType.contexts, InputVarType.iterator].includes(props.inputs[0]?.type))
  const isContext = computed(()=>props.inputs[0]?.type === InputVarType.contexts);
  const handleAddContext = () => {
      const key = props.inputs[0].variable
      props.values[key].push(isContext ? RETRIEVAL_OUTPUT_STRUCT : '')
      props.onChange(props.values)
  }

</script>

